<?php


namespace App\Services;

use App\Models\CheckMint;
use App\Models\MillProduct;
use App\Models\User;
use App\Models\UserAsset;
use App\Models\UserMillsCounter;
use App\Models\UserWallet;
use App\Models\UserWithdraw;
use App\Services\Base\CacheService;
use App\Services\Base\HelpService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BlockChainServices
{
    public static function import($params)
    {
        self::checkWithdraw($params);
    }


    public static function keyAddress($chain)
    {
        return "address:{$chain}";
    }


    public static function addressSet($chain, $address)
    {
        CacheService::sAdd(
            self::keyAddress($chain),
            $address
        );
    }

    public static function delAddressSet($chain, $address)
    {
        CacheService::sRem(
            self::keyAddress($chain),
            $address
        );
    }

    public static function addressFlush($chain)
    {
        CacheService::del(self::keyAddress($chain));
    }


    public static function keyContract($chain)
    {
        return "contract:{$chain}";
    }

    public static function contractSet($chain, $address)
    {
        CacheService::sAdd(
            self::keyContract($chain),
            $address
        );
    }

    public static function contractFlush($chain)
    {
        CacheService::del(self::keyContract($chain));
    }

    public static function checkWithdraw($params)
    {
        try {
            /**
             * @var $user_withdraw UserWithdraw
             */
            $user_withdraw = UserWithdraw::query()->where("executed_tx", $params['tx_id'])->first();
            if ($user_withdraw && $user_withdraw->tx_status == TX_STATUS_SEND) {
                $user_withdraw->tx_status = TX_STATUS_SUCCESS;
                $user_withdraw->status = TRADE_STATUS_SUCCESS;
                $user_withdraw->executed_at = date("Y-m-d H:i:s", floor($params['timestamp'] / 1000));
                $user_withdraw->save();
                return true;
            }
        } catch (\Exception $e) {
            HelpService::forceLog($e, "checkWithdraw", 'chain');
        }

        return false;
    }

}
